package com.benshou.bsoa.thread;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ThreadPoolUtils 工具类
 * 提供线程池的创建、任务提交、关闭等操作
 */
public class ThreadPoolUtils {

    // 默认的核心线程数
    private static final int DEFAULT_CORE_POOL_SIZE = Runtime.getRuntime().availableProcessors();

    // 默认的最大线程数
    private static final int DEFAULT_MAX_POOL_SIZE = DEFAULT_CORE_POOL_SIZE * 2;

    // 默认的线程存活时间
    private static final long DEFAULT_KEEP_ALIVE_TIME = 60L;

    // 线程池实例（懒加载）
    private static volatile ExecutorService executorService;

    /**
     * 获取默认的线程池实例
     *
     * @return ExecutorService 线程池实例
     */
    public static ExecutorService getExecutorService() {
        if (executorService == null) {
            synchronized (ThreadPoolUtils.class) {
                if (executorService == null) {
                    executorService = createThreadPool(DEFAULT_CORE_POOL_SIZE, DEFAULT_MAX_POOL_SIZE, DEFAULT_KEEP_ALIVE_TIME);
                }
            }
        }
        return executorService;
    }

    /**
     * 创建一个自定义的线程池
     *
     * @param corePoolSize    核心线程数
     * @param maxPoolSize     最大线程数
     * @param keepAliveTime   线程空闲保持时间
     * @return ExecutorService 线程池实例
     */
    public static ExecutorService createThreadPool(int corePoolSize, int maxPoolSize, long keepAliveTime) {
        return new ThreadPoolExecutor(
                corePoolSize,
                maxPoolSize,
                keepAliveTime,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(),
                new CustomThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy()  // 拒绝策略：当队列满时抛出异常
        );
    }

    /**
     * 提交一个任务到默认线程池
     *
     * @param task 要提交的任务
     */
    public static void submit(Runnable task) {
        getExecutorService().submit(task);
    }

    /**
     * 提交一个任务到默认线程池，并获取 Future 对象
     *
     * @param task 要提交的任务
     * @param <T>  返回值类型
     * @return Future 对象
     */
    public static <T> Future<T> submit(Callable<T> task) {
        return getExecutorService().submit(task);
    }

    /**
     * 关闭线程池
     */
    public static void shutdown() {
        if (executorService != null) {
            executorService.shutdown();
        }
    }

    /**
     * 立即关闭线程池，尝试停止所有正在执行的任务
     */
    public static void shutdownNow() {
        if (executorService != null) {
            executorService.shutdownNow();
        }
    }

    /**
     * 判断线程池是否已关闭
     *
     * @return 如果线程池已关闭，返回 true；否则返回 false
     */
    public static boolean isShutdown() {
        return executorService != null && executorService.isShutdown();
    }

    /**
     * 判断线程池是否已终止
     *
     * @return 如果线程池已终止，返回 true；否则返回 false
     */
    public static boolean isTerminated() {
        return executorService != null && executorService.isTerminated();
    }

    /**
     * 等待线程池中的所有任务完成
     *
     * @param timeout 等待的最大时间
     * @param unit    时间单位
     * @return 如果任务在超时时间内完成，则返回 true；否则返回 false
     * @throws InterruptedException 中断异常
     */
    public static boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException {
        if (executorService != null) {
            return executorService.awaitTermination(timeout, unit);
        }
        return true;
    }

    /**
     * 自定义线程工厂类，用于创建线程并命名线程
     */
    private static class CustomThreadFactory implements ThreadFactory {
        private final AtomicInteger threadNumber = new AtomicInteger(1);
        private final String namePrefix = "custom-thread-pool-";

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r, namePrefix + threadNumber.getAndIncrement());
            if (thread.isDaemon()) {
                thread.setDaemon(false);
            }
            if (thread.getPriority() != Thread.NORM_PRIORITY) {
                thread.setPriority(Thread.NORM_PRIORITY);
            }
            return thread;
        }
    }
}
